package logic

import (
	"cartsrv/cart"
	"cartsrv/internal/svc"
	"cartsrv/models/mysql"
	"cartsrv/models/redisinit"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cart.CartAddRequest) (*cart.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	r := mysql.Goods{}

	err := mysql.Db.Where("goods_id = ? ", in.GoodsId).Find(&r).Error
	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	if r.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	
	if r.GoodsStock < r.GoodsNumber {
		return nil, fmt.Errorf("库存不足")
	}
	redisinit.AddCart(int(in.UserId), int(in.GoodsId), int(in.GoodsNumber), in.GoodsName, float64(in.Price))
	return &cart.CartAddResponse{}, nil
}
